﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.Data.OleDb;
using System.IO;
using System.Net;
using System.Diagnostics;

namespace mobo
{
    public partial class Form1 : KryptonForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        //form load event
        private void BaseLoad(object sender, EventArgs e)
        {
            LoadLibrary(); //loads main library 
            tracklist.Sort(tracklist.Columns[0], ListSortDirection.Ascending); //sorts the tracklist
        }

        //loadlibrary event
        private void LoadLibrary()
        {
            String provider = Global.ConnectionString; //gets connection string to connect with the database
            String sql = "SELECT * FROM Library"; //sql command

            OleDbConnection con = new OleDbConnection(provider); //sets the connection
            OleDbCommand cmd = new OleDbCommand(sql, con); //sets the command

            con.Open(); //opens connection

            //loads data into the datagridview
            cmd.CommandType = CommandType.Text;
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            DataTable tracks = new DataTable();
            da.Fill(tracks);
            tracklist.DataSource = tracks;

            tracklist.Columns[0].HeaderText = "#"; //changes first header from 'id' to '#'
            tracklist.Columns[5].Visible = false; //makes directory column invisible
        }

        //form shown event
        private void LoadPlugins(object sender, EventArgs e)
        {
            try
            {
                Global.Plugins.FindPlugins(Application.StartupPath + @"\plugins"); //searches plugins in the plugins folder

                //adds found plugins to 'playlist' menu
                foreach (Types.AvailablePlugin pluginOn in Global.Plugins.AvailablePlugins)
                {
                    ToolStripMenuItem subitem = new ToolStripMenuItem(pluginOn.Instance.Name, null, LoadPluginToPanel); //creates the submenu item
                    menuplugins.DropDownItems.Add(subitem);
                    subitem = null; //changes subitem value to null so multiple plugins can be added with the loop
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString() + ". Search for help with this error at the Help menu >> Mobo Help \nPress OK to continue", "Mobo Player", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }

            //CheckForUpdates();
        }

        //mobohelp, about click event
        private void HelpMenu(object sender, EventArgs e)
        {
            if ((ToolStripMenuItem)sender == mobohelp)
            {
                Process.Start("http://mobo.codeplex.com/"); //redirects user to mobo home page (opens the user default browser)
            }
            else if ((ToolStripMenuItem)sender == about)
            {
                MessageBox.Show(" Mobo Player \n Created and designed by Pedro Martins \n version 0.2 alpha", "About Mobo");
            }
        }

        //checkforupdates event
        private void CheckForUpdates()
        {
            //try
            //{
            //    WebClient Client = new WebClient();
            //    Stream str = Client.OpenRead("http://blackmedia.sourceforge.net/update.txt");
            //    StreamReader r = new StreamReader(str);
            //    String input = null;

            //    while ((input = r.ReadLine()) != null)
            //    {
            //        if (input.StartsWith("file:"))
            //        {
            //            String p = input.Remove(0, 5);
            //            Global.ReleasePath = p;
            //        }
            //        else if (input.StartsWith("version:"))
            //        {
            //            String v = input.Remove(0, 8);
            //            if (v == Global.Version)
            //            {
            //                return;
            //            }
            //            else
            //            {
            //                Form2 updater = new Form2();
            //                updater.uversion.Text = Global.Version;
            //                updater.cversion.Text = v;
            //                updater.path.Text = Global.ReleasePath;
            //                updater.ShowDialog();
            //            }

            //        }
            //    }
            //    r.Close();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.ToString());
            //}
        }

        //loadpluginstopanel event
        private void LoadPluginToPanel(object sender, EventArgs e)
        {
            //gets the plugin name
            Types.AvailablePlugin selectedPlugin = Global.Plugins.AvailablePlugins.Find(((ToolStripMenuItem)sender).Text);

            if (selectedPlugin != null)
            {
                this.pluginspanel.Controls.Clear(); //clears any plugin loaded earlier to the panel
                selectedPlugin.Instance.MainInterface.Dock = DockStyle.Fill; //fills the plugin control to the plugins panel
                this.pluginspanel.Controls.Add(selectedPlugin.Instance.MainInterface); //adds plugins control to the plugins panel
            }
        }

        //form formclosing event
        private void ClosePlugins(object sender, FormClosingEventArgs e)
        {
            Global.Plugins.ClosePlugins(); //close running plugin
            media.Ctlcontrols.stop(); //stops any playing file
        }

        //tracklist mouseclick event
        private void ClearSelection(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hit = tracklist.HitTest(e.X, e.Y); //creates hittestinfo

            if (hit.Type == DataGridViewHitTestType.None) //if the user clicked outside the cells / rows / columns
                tracklist.ClearSelection(); //clears selection
        }

        //tracklist celldoubleclick event
        private void SelectTrack(object sender, DataGridViewCellEventArgs e)
        {
            seekBar.Value = 0; //clears the seeekbar value
            tposition.Stop(); //if another file was playing, stops the position timer
            //System.Threading.Thread.Sleep(1000);
            mediaposition.Text = "0:00"; //changes postition text to its default value

            int rowindex = e.RowIndex; //gets the selected row index
            String dir = tracklist.Rows[rowindex].Cells[5].Value.ToString(); //gets the item's directory information  
            if (File.Exists(dir)) //if item's directory is correct
            {
                Global.File = TagLib.File.Create(dir); //creates new instance of blackmp3.File to read mp3 tags
                media.URL = dir; //sets the current media url value to the selected item's directory
                media.Ctlcontrols.play(); //plays the file
            }
            else //if directory is not correct
            {
                MessageBox.Show("Unabled to load file. It directory was deleted, moved or renamed", "Mobo Player"); //the file does not exist, or its directory was deleted, renamed or moved
            }
        }

        //togglepluginpanel click event
        private void TogglePluginPanel(object sender, EventArgs e)
        {
            if (pluginspanel.Visible) //if plugins panel is opened
            {
                togglepluginpanel.Text = "show"; //changes togglepluginpanel text
                pluginspanel.Visible = false; //makes plugins panel invisible
                rightborder.Visible = false; //makes rightborder invisible
                mediacontainer.Width += 156; //fills mediacontainer
                showplugins.Checked = false;
            }
            else //else if panel is closed
            {
                togglepluginpanel.Text = "hide"; //changes togglepluginpanel text
                pluginspanel.Visible = true; //makes plugins panel visible
                rightborder.Visible = true; //makes rightborder visible
                mediacontainer.Width -= 156; //makes mediacontainer smaller to fit plugins panel
                showplugins.Checked = true;
            }
        }

        //importfile click event
        private void ShowFileDialog(object sender, EventArgs e)
        {
            filedialog.ShowDialog(); //show import file dialog
        }

        //filedialog fileok event
        private void ImportFile(object sender, CancelEventArgs e)
        {
            if (filedialog.FileName.ToLower().EndsWith(".mp3"))
            {
                try
                {
                    Import(filedialog.FileName, "Library"); //imports file to the library
                    media.URL = filedialog.FileName;
                    media.Ctlcontrols.play();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else if (filedialog.FileName.ToLower().EndsWith(".mp4"))
            {
                //Global.IsMovie = true;
                //Global.File = TagLib.Mpeg4.File.Create(filedialog.FileName);
                //movie.Visible = true;
                //movie.URL = filedialog.FileName;
            }
        }

        //folderbrowser click event
        private void ImportFolder(object sender, EventArgs e)
        {
            String folder; //string to retrieve folder path
            int count = 0; //int to retrieve files count
            int errors = 0; //int to retrieve errors count

            DialogResult fbrowser = folderbrowser.ShowDialog(); //shows the folder dialog

            if (fbrowser == DialogResult.OK) //if the user chose a folder
            {
                messagepanel.Visible = true; //shows the message panel 
                folder = folderbrowser.SelectedPath; //gets the selected folder path

                DirectoryInfo dir = new DirectoryInfo(folder); //creates a directory info with the selected path
                foreach (FileInfo f in dir.GetFiles()) //foreach file in the directory
                {
                    if (f.Extension.ToLower() == ".mp3") //if it is a mp3 file
                    {
                        try
                        {
                            Import(f.FullName, "Library"); //import the mp3 file to the library
                            count++;
                            Global.File = TagLib.File.Create(f.FullName); //creates a TagLib.File to retrieve mp3 tags from the file
                            String title = Global.File.Tag.Title; //gets the title
                            String artist = Global.File.Tag.FirstArtist; //gets the artist
                            messagelabel.Text = String.Format("{0} - {1}", title, artist); //sets the message label text to the 'Title - Artist' format (from the current processing file) 
                            messagelabel.Update(); //updates the message label text
                            Application.DoEvents(); //prevents the app from freezing
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            errors++; //increases errors count
                        }
                    }
                }
                proc.Visible = false; //makes proc label invisible
                if (count == 0) //if there weren't any mp3 files in the directory
                {
                    //shows the 'no mp3 files' message
                    messagelabel.Text = "Unabled to find any mp3 file. Make sure you selected the correct folder";
                }
                else
                {
                    //shows the files and errors count
                    messagelabel.Text = String.Format("{0} files were imported to the library. {1} error(s)", count.ToString(), errors.ToString());
                }
                tmessage.Start(); //starts message timer
            }
        }

        private void MessageTimer(object sender, EventArgs e)
        {
            messagepanel.Visible = false; //makes message panel invisible
            proc.Visible = true; //makes proc label visible
            tmessage.Stop(); //stops the message timer
        }

        //import event
        private void Import(String path, String table)
        {
            Global.File = TagLib.File.Create(path); //creates a blackmp3.File to retrieve mp3 tags from the file

            String id = CalculateId(table); //calculates the new id
            String title = Global.File.Tag.Title; //gets the title
            String artist = Global.File.Tag.FirstArtist; //gets the artist
            String album = Global.File.Tag.Album; //gets the album
            String duration = Global.File.Properties.Duration.Minutes.ToString() + ":" + Global.File.Properties.Duration.Seconds.ToString(); //gets the duration time (format #:##)
            String dir = path; //gets the file's directory and replaces any " ' " char, so the db doesn't get confused

            if (title == null)
            {
                title = Path.GetFileName(dir);
            }
            else
            {
                title = Global.File.Tag.Title;
            }

            if (artist != null)
                artist = Global.File.Tag.FirstArtist;

            if (album != null)
                album = Global.File.Tag.Album;

            if (Global.File.Properties.Duration.Seconds < 10)
                duration = Global.File.Properties.Duration.Minutes.ToString() + ":0" + Global.File.Properties.Duration.Seconds.ToString();

            String provider = Global.ConnectionString; //gets connection string to connect with the database 
            String sql = "INSERT into " + table + " (id,title,artist,album,duration,directory) VALUES(\"" + id + "\", \"" + title + "\", \"" + artist + "\", \"" + album + "\", \"" + duration + "\", \"" + dir + "\")"; //sql command

            OleDbConnection con = new OleDbConnection(provider); //sets the connection
            OleDbCommand command = new OleDbCommand(sql, con); //sets the command

            con.Open(); //opens connection

            command.ExecuteNonQuery(); //executes the command
            command.Dispose(); //disposes the command
            con.Close(); //closes the connection

            LoadLibrary(); //loads library to tracklist again
        }

        //calculateid event
        private String CalculateId(String table)
        {
            String id = String.Empty; //creates an empty string for id value

            OleDbConnection con = new OleDbConnection(Global.ConnectionString); //gets connection string to connect with the database 
            OleDbCommand command = new OleDbCommand("SELECT count(*) from " + table, con); //sql command

            int count = -1; //creates int for track count

            try
            {
                con.Open(); //opens the connection
                count = (int)command.ExecuteScalar(); //calls executescalar to send command
            }
            finally
            {
                if (con != null) //if the connection isn't null
                {
                    con.Close(); //closes the connection
                }
            }

            int idvalue = count + 1; //creates a new int to get the new id value (tracks count + 1)
            id = idvalue.ToString() + "."; //sets the id value to the id string (format ##.)

            if (idvalue < 10) //if id is smaller than 10
                id = "0" + id; //add an zero so the id created is in the right format (##.)

            return id; //returns id
        }

        //prev, next, pause, play mouseenter event
        private void HoverIn(object sender, EventArgs e)
        {
            //toggles hover mode media control buttons images
            if ((PictureBox)sender == play)
            {
                play.Image = mobo.Properties.Resources.play_hover;
            }
            else if ((PictureBox)sender == pause)
            {
                pause.Image = mobo.Properties.Resources.pause_hover;
            }
        }

        //prev, next, pause, play mouseleave event
        private void HoverOut(object sender, EventArgs e)
        {
            //toggles normal mode media control buttons images
            if ((PictureBox)sender == play)
            {
                play.Image = mobo.Properties.Resources.play;
            }
            if ((PictureBox)sender == pause)
            {
                pause.Image = mobo.Properties.Resources.pause;
            }
        }

        //prev, next, pause, play mousedown event
        private void ClickIn(object sender, MouseEventArgs e)
        {
            //toggles click mode media control buttons images
            if ((PictureBox)sender == play)
            {
                play.Image = mobo.Properties.Resources.play_click;
            }
            else if ((PictureBox)sender == pause)
            {
                tstop.Start(); //start stop timer, so if the users keep the pause button clicked for 700ms, the media is stopes
                pause.Image = mobo.Properties.Resources.pause_click;
            }
        }

        //prev, next, pause, play mouseup event
        private void ClickOut(object sender, MouseEventArgs e)
        {
            //toggles hover mode media control buttons images
            if ((PictureBox)sender == play)
            {
                play.Image = mobo.Properties.Resources.play;
            }
            else if ((PictureBox)sender == pause)
            {
                tstop.Stop(); //stops the stop timer, so if the user didn't keep the pause button cliked for 700ms, it won't stop the media
                pause.Image = mobo.Properties.Resources.pause;
            }
        }

        //prev, next, pause, play click event
        public void MediaControl(object sender, EventArgs e)
        {
            if ((PictureBox)sender == play)
            {
                if (media.URL == String.Empty) //if there isn't any file loaded to the media control
                    return; //do nothing
                media.Ctlcontrols.play(); //plays the current file loaded to the media control
                pause.Visible = true; //toggles pause button visibility
            }
            else if ((PictureBox)sender == pause)
            {
                media.Ctlcontrols.pause(); //pauses the current file loaded to the media control
                pause.Visible = false; //toggles pause button visibility
            }
        }

        //menu play, pause, stop click event
        private void MenuMediaControl(object sender, EventArgs e)
        {
            if ((ToolStripMenuItem)sender == menuplay)
            {
                if (media.URL == String.Empty) //if there isn't any file loaded to the media control
                    return; //do nothing
                media.Ctlcontrols.play(); //plays the current file loaded to the media control
                pause.Visible = true; //toggles pause button visibility
            }
            else if ((ToolStripMenuItem)sender == menupause)
            {
                media.Ctlcontrols.pause(); //pauses the current file loaded to the media control
                pause.Visible = false; //toggles pause button visibility
            }
            else if ((ToolStripMenuItem)sender == menustop)
            {
                media.Ctlcontrols.stop(); //pauses the current file loaded to the media control
                pause.Visible = false; //toggles pause button visibility
            }
        }

        private void MenuVolumeControl(object sender, EventArgs e)
        {
            if ((ToolStripMenuItem)sender == v0 || (ToolStripMenuItem)sender == muted)
            {
                media.settings.mute = true;
                muted.Checked = true;
            }
            else if ((ToolStripMenuItem)sender == v20)
            {
                media.settings.mute = false;
                media.settings.volume = 20;
                muted.Checked = false;
            }
            else if ((ToolStripMenuItem)sender == v50)
            {
                media.settings.mute = false;
                media.settings.volume = 50;
                muted.Checked = false;
            }
            else if ((ToolStripMenuItem)sender == v70)
            {
                media.settings.mute = false;
                media.settings.volume = 70;
                muted.Checked = false;
            }
            else if ((ToolStripMenuItem)sender == v100)
            {
                media.settings.mute = false;
                media.settings.volume = 100;
                muted.Checked = false;
            }
        }

        //tstop tick event
        private void Stop(object sender, EventArgs e)
        {
            media.Ctlcontrols.stop(); //stops the current file loaded to the media control
            tstop.Stop(); //stops the timer
        }

        //media playstatechange event
        private void PlayStateChanged(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            if (media.playState == WMPLib.WMPPlayState.wmppsPlaying)
            {
                pause.Visible = true;
                Global.File = TagLib.File.Create(media.URL);
                Int32 TotalSeconds = Global.File.Properties.Duration.Minutes * 60 + Global.File.Properties.Duration.Seconds;
                title.Text = Global.File.Tag.Title;
                artist.Text = Global.File.Tag.FirstArtist;
                duration.Text = Global.File.Properties.Duration.Minutes.ToString() + ":" + Global.File.Properties.Duration.Seconds.ToString(); //gets the duration time (format #:##)

                if (Global.File.Tag.Title == null)
                {
                    title.Text = Path.GetFileNameWithoutExtension(media.URL);
                }

                if (Global.File.Properties.Duration.Seconds < 10)
                    duration.Text = Global.File.Properties.Duration.Minutes.ToString() + ":0" + Global.File.Properties.Duration.Seconds.ToString();

                seekBar.Maximum = TotalSeconds;
                tposition.Start();

                GetCover();
            }
            else if (media.playState == WMPLib.WMPPlayState.wmppsPaused)
            {
                pause.Visible = false;
                tposition.Stop();
            }
            else if (media.playState == WMPLib.WMPPlayState.wmppsStopped)
            {
                pause.Visible = false;
                seekBar.Value = 0;
                tposition.Stop();
                System.Threading.Thread.Sleep(1000);
                mediaposition.Text = "0:00";
                duration.Text = "0:00";
                title.Text = "Title";
                artist.Text = "Artist";
            }
            else if (media.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
            {
                pause.Visible = false;
                seekBar.Value = 0;
                tposition.Stop();
                System.Threading.Thread.Sleep(1000);
                mediaposition.Text = "0:00";
                duration.Text = "0:00";
                title.Text = "Title";
                artist.Text = "Artist";
                PlayNext();
            }
        }

        private void PlayNext()
        {
            String path = String.Empty;

            for (int i = 0; i <= tracklist.Rows.Count; i++)
            {
                if (tracklist.Rows[i].Cells[5].Value.ToString() == media.URL)
                {
                    if (i == tracklist.Rows.Count - 1)
                    {
                        path = tracklist.Rows[0].Cells[5].Value.ToString();
                        if (File.Exists(path))
                        {
                            media.URL = path;
                            tplaynext.Start();
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        path = tracklist.Rows[i + 1].Cells[5].Value.ToString();
                        if (File.Exists(path))
                        {
                            media.URL = path;
                            tplaynext.Start();
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }

        private void PlayNextTimer(object sender, EventArgs e)
        {
            media.Ctlcontrols.play();
            tplaynext.Stop();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            seekBar.Value++;

            String currentPosition = media.Ctlcontrols.currentPositionString;
            if (currentPosition.StartsWith("0"))
                currentPosition = currentPosition.Remove(0, 1);
            mediaposition.Text = currentPosition;
            Application.DoEvents();
        }

        private void searchplugins_MouseEnter(object sender, EventArgs e)
        {
            searchplugins.ForeColor = Color.Teal;
        }

        private void searchplugins_MouseLeave(object sender, EventArgs e)
        {
            searchplugins.ForeColor = Color.Silver;
        }

        private void label8_MouseEnter(object sender, EventArgs e)
        {
            ((Label)sender).ForeColor = Color.Teal;
        }

        private void label8_MouseLeave(object sender, EventArgs e)
        {
            ((Label)sender).ForeColor = Color.Silver;
        }

        private void label3_Click(object sender, EventArgs e)
        {
            if ((Label)sender == file)
            {
                menufile.ShowDropDown();
            }
            else if ((Label)sender == edit)
            {
                menuedit.ShowDropDown();
            }
            else if ((Label)sender == view)
            {
                menuview.ShowDropDown();
            }
            else if ((Label)sender == control)
            {
                menucontrol.ShowDropDown();
            }
            else if ((Label)sender == plugins)
            {
                menuplugins.ShowDropDown();
            }
            else if ((Label)sender == help)
            {
                menuhelp.ShowDropDown();
            }
        }

        //tracklist userdeletingrow event
        private void DeleteRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            Delete(e.Row, "Library");
            if (e.Row.Cells[5].Value.ToString() == media.URL)
            {
                media.Ctlcontrols.stop();
                media.URL = String.Empty;
            }
        }

        //delete event
        private void Delete(DataGridViewRow row, String table)
        {
            String id = row.Cells[0].Value.ToString();

            String provider = Global.ConnectionString;
            String sql = "DELETE from " + table + " where id = '" + id + "'";

            OleDbConnection con = new OleDbConnection(provider);
            OleDbCommand command = new OleDbCommand(sql, con);

            con.Open();
            command.ExecuteNonQuery();
            //UpdateId("Library");
            command.Dispose();
            con.Close();
        }

        private void dfgToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tracklist.SelectAll();
        }

        private void deleteitem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in tracklist.SelectedRows)
            {
                Delete(row, "Library");
                tracklist.Rows.Remove(row);
            }
        }

        private void tracklist_SelectionChanged(object sender, EventArgs e)
        {
            if (tracklist.SelectedRows.Count > 0)
            {
                deleteitem.Enabled = true;
            }
            else
            {
                deleteitem.Enabled = false;
            }
        }

        private void sb_Scroll(object sender, EventArgs e)
        {
            media.Ctlcontrols.currentPosition = seekBar.Value;
        }

        private void searchplugins_Click(object sender, EventArgs e)
        {
            Process.Start("http://mobo.codeplex.com/");
        }

        private void GetCover()
        {
            if (Global.File.Tag.Pictures.Length >= 1)
            {
                var bin = (byte[])(Global.File.Tag.Pictures[0].Data.Data);
                cover.Image = Image.FromStream(new MemoryStream(bin)).GetThumbnailImage(169, 159, null, IntPtr.Zero);
            }
            else
            {
                cover.Image = mobo.Properties.Resources.no_cover;
            }
        }

        private void closecover_Click(object sender, EventArgs e)
        {
            sidebar.Panel2Collapsed = true;
            covermenu.Checked = false;
        }

        private void covermenu_Click(object sender, EventArgs e)
        {
            if (!covermenu.Checked)
            {
                sidebar.Panel2Collapsed = true;
                covermenu.Checked = false;
            }
            else
            {
                sidebar.Panel2Collapsed = false;
                covermenu.Checked = true;
            }
        }


        //private void UpdateId(String table)
        //{
        //    OleDbConnection con = new OleDbConnection(Global.ConnectionString);
        //    OleDbCommand command = new OleDbCommand("SELECT * from " + table, con);

        //    String oldid;
        //    String id;
        //    int count = 1;

        //    try
        //    {
        //        con.Open();

        //        //call executescalar to send command
        //        //count = (int)command.ExecuteScalar();

        //        OleDbDataReader reader = command.ExecuteReader();
        //        while (reader.Read())
        //        {
        //            oldid = reader.GetString(0);
        //            id = count.ToString() + ".";
        //            if (count < 10)
        //                id = "0" + id;

        //            MessageBox.Show("Old id = " + oldid);
        //            MessageBox.Show("New id = " + id);

        //            OleDbConnection conn = new OleDbConnection(Global.ConnectionString);
        //            OleDbCommand cmd = new OleDbCommand("UPDATE " + table + " SET id = '" + id + "' WHERE id = '" + oldid + "'", con);

        //            try
        //            {
        //                conn.Open();
        //                cmd.ExecuteNonQuery();
        //                cmd.Dispose();
        //                conn.Close();
        //                count++;
        //            }
        //            catch
        //            {
        //                MessageBox.Show("Unabled to update item id");
        //            }
        //        }
        //    }
        //    finally
        //    {
        //        if (con != null)
        //            con.Close();
        //        LoadLibrary();
        //    }
        //}
    }
}
